package org.example;

public class Lexer {
    private String expression;
    private int position;
    private String currentToken;
    public Lexer(String expression) {
        this.expression = expression;
        this.position = 0;
        this.currentToken = null;
    }

    public String nextToken() {
        // 如果到达字符串末尾，直接返回 null
        if (position >= expression.length()) {
            return null;
        }
        char currentChar = expression.charAt(position);
        // 跳过空格
        while (position < expression.length() && Character.isWhitespace(currentChar)) {
            position++;
            if (position < expression.length()) {
                currentChar = expression.charAt(position);
            }
        }
        // 处理数字（包括整数和小数）
        if (Character.isDigit(currentChar)) {
            StringBuilder number = new StringBuilder();
            while (position < expression.length() && (Character.isDigit(expression.charAt(position)) || expression.charAt(position) == '.')) {
                number.append(expression.charAt(position));
                position++;
            }
            currentToken = number.toString();
            return currentToken;
        }
        // 处理操作符和括号
        switch (currentChar) {
            case '+': case '-': case '*': case '/': case '^':
                currentToken = String.valueOf(currentChar);
                position++;
                return currentToken;
            case '(': case ')':
                currentToken = String.valueOf(currentChar);
                position++;
                return currentToken;
            default:
                throw new RuntimeException("非法字符: " + currentChar);  // 抛出异常来处理非法字符
        }
    }
}
